package com.china.school.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.Callable;

@RestController
public class CallableController {

    @GetMapping("/testCallable")
    public Callable<String> test(){
        System.out.println("主线程开始时间" + LocalDateTime.now()  + "线程名称" + Thread.currentThread().getName());
        Callable<String> result = () -> {
            System.out.println("新线程开始时间" + LocalDateTime.now()  + "新线程名称" + Thread.currentThread().getName());
            Thread.sleep(4000);
            System.out.println("新线程返回时间" + LocalDateTime.now() + "新线程名称" + Thread.currentThread().getName());
            return "处理成功";
        };
        System.out.println("主线程返回时间" + LocalDateTime.now() + "主线程名称" + Thread.currentThread().getName());
        return result;
    }
    @GetMapping("/testDeferredResult")
    public DeferredResult<String> testDeferredResult(){
        System.out.println("主线程开始时间" + LocalDateTime.now()  + "线程名称" + Thread.currentThread().getName());
        DeferredResult<String> result = new DeferredResult<String>(3000L,"超时");
        new Thread(){
            @Override
            public void run() {
                System.out.println("新线程开始时间" + LocalDateTime.now()  + "新线程名称" + Thread.currentThread().getName());
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("新线程返回时间" + LocalDateTime.now() + "新线程名称" + Thread.currentThread().getName());
                result.setResult("处理成功");
             }
        }.start();

        System.out.println("主线程返回时间" + LocalDateTime.now() + "主线程名称" + Thread.currentThread().getName());
        return result;
    }
}
